#include <pthread.h>
#include <iostream>
#include <unistd.h>

#include "mutexEncapsulation"

using namespace MutexModule;

class ThreadData
{
public:
    ThreadData(std::string name, Mutex &mutex)
        : _name(name), _pmutex(&mutex)
    {
    }
    ~ThreadData()
    {
    }

    std::string _name;
    Mutex *_pmutex;
};

int ticket = 1000;
void *Routine(void *arg)
{
    ThreadData *td = static_cast<ThreadData *>(arg);
    while (1)
    {
        LockGuard lg(td->_pmutex);
        if (ticket > 0)
        {
            usleep(1000);
            printf("%s sells ticket : %d\n", td->_name.c_str(), ticket);
            ticket--;
        }
        else
        {
            break;
        }
    }
    return nullptr;
}
int main()
{
    pthread_mutex_t lock;
    Mutex mutex(lock);
    pthread_t t1, t2, t3, t4;

    ThreadData *td1 = new ThreadData("thread-1", mutex);
    pthread_create(&t1, nullptr, Routine, td1);

    ThreadData *td2 = new ThreadData("thread-2", mutex);
    pthread_create(&t2, nullptr, Routine, td2);

    ThreadData *td3 = new ThreadData("thread-3", mutex);
    pthread_create(&t3, nullptr, Routine, td3);

    ThreadData *td4 = new ThreadData("thread-4", mutex);
    pthread_create(&t4, nullptr, Routine, td4);

    pthread_join(t1, nullptr);
    pthread_join(t2, nullptr);
    pthread_join(t3, nullptr);
    pthread_join(t4, nullptr);

    return 0;
}